package com.ttbj.product.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.ttbj.core.protocol.http.HttpInvokeService;
import com.ttbj.core.protocol.http.HttpProviderConf;
import com.ttbj.core.response.ResponseModel;
import com.ttbj.core.response.enums.ResponseCodeEnums;
import com.ttbj.core.util.JsonUtil;
 

@Controller
@RequestMapping("/dubbo")
public class DubboController {
	private static Logger logger = LoggerFactory.getLogger(DubboController.class);
	@Autowired
	private HttpInvokeService httpInvokeService;
	@Autowired
	private HttpProviderConf httpProviderConf;

	@ResponseBody
	@RequestMapping(value = "/{service}/{method}", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	public String dubboFacade(@PathVariable String service, @PathVariable String method, @RequestParam String parametersJson) {
		logger.debug("parametersJson:{}", JSON.toJSONString(parametersJson));
		ResponseModel<String> responseModel = new ResponseModel<String>();
		if (!CollectionUtils.isEmpty(httpProviderConf.getUsePackage())) {
			boolean isPac = false;
			for (String pac : httpProviderConf.getUsePackage()) {
				if (service.startsWith(pac)) {
					isPac = true;
					break;
				}
			}
			if (!isPac) {
				// 调用的是未经配置的包
				logger.error("service is not correct,service=" + service);
				responseModel.setResponse(ResponseCodeEnums.FAILURE);
				responseModel.setMsg("service is not correct,service=" + service);
			}
			String invoke = httpInvokeService.invoke(service, method, parametersJson);
			logger.debug("callback :" + invoke);
			return invoke;
		} else {
			return JsonUtil.beanToJson(responseModel);
		}

	}

}
